<?php
abstract class App_Model_Mapper 
{
    protected $_table;
    protected $_entityClass;
    public function __construct($id=null)
    {
        $this->_table = $this->_setTable();
    }

    abstract protected function _setTable();
  
    public function getTable()
    {
        return $this->_table;
    }
    
    public function load($id)
    {
        $row = $this->_table->find($id)->current();
        $entity= new $this->_entityClass;
        foreach ($this->_map as $key=>$value){
            $entity->$key = $row->$value;	
        }
        return $entity;
    } 
    
    public function save($entity, array $ignore = array())
    {
    	$data = array();
    	if(!$entity->id){
    	   foreach ($this->_map as $key=>$value){
    	       $data[$value] = $entity->$key;
    	   }
    	$entity->id = $this->_table->insert($data);
    	} else {
    	   foreach ($this->_map as $key=>$value){
    	       foreach($ignore as $ignoreValue){
    	           if($ignoreValue == $value){
    	               continue 2;
    	           }
    	       }
               $data[$value] = $entity->$key;
           }
           $this->_table->update($data, 'id = ' . (int) $entity->id);
    	}
    	return $entity;
    }
    
    public function delete($entry)
    {
        if (is_int($entry)){
        	$where = $this->_getGateway()->getAdapter()
                ->quoteInto('id = ?', $entry);
        } else { 
            $where = $this->_table->getAdapter()
                ->quoteInto('id = ?', $entry->id);
        }
    	$this->_table->delete($where);
    }
    
    public function fill($entity, array $data){
    	foreach($this->_map as $key => $value){
    		if($data[$value]){
    		  $entity->$key = $data[$value];
    		}
    	}
    	return $entity;
    }
    
    public function getArray($rowset)
    {
    	$array = array();
        if(!is_array($rowset)){
            $rowset = $rowset->toArray();
        }
    	foreach($rowset as $row){
    		$entity = new $this->_entityClass();
    		foreach ($this->_map as $key => $value){
    			$entity->$key = $row[$value];
    		}
    		$array[] = $entity;
    	}
    	return $array;
    }
}